package com.viu.technology.controller;

import com.viu.technology.dto.Result;
import com.viu.technology.dto.ResultCode;
import com.viu.technology.po.User;
import com.viu.technology.service.user.UserService;
import com.viu.technology.service.user.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping("/userInfo/{userId}")
    public User getUserInfo(@PathVariable String userId) {
        User user = userService.getUserAndRoleById(userId);
        return user;
    }


    @PostMapping("/register")
    public Result insertUser(@RequestBody User user) {
        User result = userService.registerUser(user);
        if (null != result) {
            return Result.success(result);
        }
        return Result.fail(ResultCode.USER_REGISTER_FIAL);
    }


    @PostMapping(value = "/generate/token")
    public Result getToken(String phone, String password) throws AuthenticationException {

        String token = userService.login(phone, password);
        return Result.success(token);
    }

    @GetMapping("/self/info")
    public Result getUserSelfInfo() {

        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        return Result.success(user);
    }
}
